package Admin;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;

import javax.swing.AbstractButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import GroupClass.ConnectRMI;
import Project_etow.EtowInterface;

public class FloorFree extends javax.swing.JDialog {
	
	private int row,dem;
	ConnectRMI connectRMI = new ConnectRMI();
	private static String chua;
	private String click1, click2, click3;
	private  static String a1, a2, a3;
	private DefaultTableModel dtm;
	private	String floorId,floorName,statusFloor;
	private String checkVisable;
	
	public String getCheckVisable()
    {
        return checkVisable;
    }

    public void setCheckVisable(String checkVisable)
    {
        this.checkVisable = checkVisable;
    }
    private int CountFloor;
	
	public int getCountFloor()
    {
        return CountFloor;
    }

    public void setCountFloor(int countFloor)
    {
        CountFloor = countFloor;
    }
    private String townId;
    public String getTownId() {
		return townId;
	}

	public void setTownId(String townId) {
		this.townId = townId;
	}

	public FloorFree(java.awt.Frame parent, boolean modal,String idtown) {
        super(parent, modal);
        chua = idtown;
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbdulieu = new javax.swing.JTable();
        btnchoseu = new javax.swing.JButton();
        btnexit = new javax.swing.JButton();
        btnInsert = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Floor Free");

        Object colNames[] = {"", "Floor Name","Status",""};  
  	  	Object[][] data = {};
	  	dtm = new DefaultTableModel(data,colNames);  
	  	tbdulieu = new JTable(dtm);  
	  	tbdulieu.getTableHeader().setReorderingAllowed(false);
	  	tbdulieu.getColumnModel().getColumn(0).setMaxWidth(80);
  	  	tbdulieu.getColumnModel().getColumn(0).setMinWidth(80);
  	  	tbdulieu.getColumnModel().getColumn(0).setWidth(50);
  	  	
	  	tbdulieu.getColumnModel().getColumn(3).setMaxWidth(0);
  	  	tbdulieu.getColumnModel().getColumn(3).setMinWidth(0);
  		
  	  	TableColumn tc = tbdulieu.getColumnModel().getColumn(0);  
  	    tc.setCellEditor(tbdulieu.getDefaultEditor(Boolean.class));  
  	    tc.setCellRenderer(tbdulieu.getDefaultRenderer(Boolean.class));  
  	    tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
  	  	
  	  tbdulieu.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				e.consume();
				row = tbdulieu.getSelectedRow();
				click1 = tbdulieu.getValueAt(row, 1).toString();
				click2 = tbdulieu.getValueAt(row, 2).toString();
				click3 = tbdulieu.getValueAt(row, 3).toString();
				
				a1 = click1;
				a2 = click2;
				a3 = click3;
				
			}

		});
  	  	
  	  try {				 
  	    Registry registry = LocateRegistry.getRegistry(connectRMI.host,connectRMI.port);
            EtowInterface obj=(EtowInterface)registry.lookup(connectRMI.regis);
  			
  		List<GroupClass.FloorClass> x =obj.showfloorfreeoftown(chua);			
  		
  		for(GroupClass.FloorClass d:x) {
 			floorId = d.getIdfloor();
 			floorName = d.getNamefloor();
 			statusFloor = d.getStatusfloor();
 			
  	    dtm.addRow(new Object[]{new Boolean(false),floorName,statusFloor,floorId});
  		}								
  			
  		}catch (Exception ex) {
  			ex.printStackTrace();
  		}	  	    
  	    	    
        jScrollPane1.setViewportView(tbdulieu);

        btnchoseu.setText("Choose Unit");
        btnchoseu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnchoseuActionPerformed(evt);
            }
        });

        btnexit.setText("Exit");
        btnexit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnexitActionPerformed(evt);
            }
        });

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				EditFloor eF = new EditFloor(null, true, getTownId());
				eF.setCheckedit("ok");
				eF.setVisible(true);
				while (eF.isVisible() != true) {
					if (eF.getCheckedit().equals("close")) {
					    reloadtable();
						break;
					}
				}
			}
		});

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				String result = "";
				int i = JOptionPane.showConfirmDialog(null,
						"Neu Ban Da Chac Chan Hay Chon Ok", null,
						JOptionPane.YES_NO_OPTION);
				if (i == JOptionPane.YES_OPTION) {
					EtowInterface obj = null;
					Registry registry;
					try {
					     registry = LocateRegistry.getRegistry(connectRMI.host,connectRMI.port);
	                                         obj=(EtowInterface)registry.lookup(connectRMI.regis);
						dem = 0;
						for (int j = 0; j < tbdulieu.getRowCount(); j++) {
							if (tbdulieu.getValueAt(j, 0).toString() == "true") {
								try {
									dem += 1;
									result = obj.DeleteFloor(tbdulieu.getValueAt(j, 3).toString());
									if(result != "Ok")
									{
										JOptionPane.showMessageDialog(null, "" + tbdulieu.getValueAt(j, 1) + " has been deleted");
									}
									
								} catch (RemoteException e) {
									e.printStackTrace();
								}
							}
						}
						reloadtable();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});

        btnInsert.setText("Insert");
        btnInsert.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				InsertFloor iF = new InsertFloor(null, true ,getTownId());
				iF.setCheckvisable("ok");
				iF.setVisible(true);
				while (iF.isVisible() != true) {
					if (iF.getCheckvisable().equals("close")) {
					    reloadtable();
						break;
					}
				}
			}
		});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnchoseu)
                .addGap(18, 18, 18)
                .addComponent(btnInsert)
                .addGap(18, 18, 18)
                .addComponent(btnEdit)
                .addGap(18, 18, 18)
                .addComponent(btnDelete)
                .addGap(18, 18, 18)
                .addComponent(btnexit)
                .addContainerGap(49, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnchoseu)
                    .addComponent(btnInsert)
                    .addComponent(btnEdit)
                    .addComponent(btnDelete)
                    .addComponent(btnexit))
                .addGap(0, 17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FloorFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FloorFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FloorFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FloorFree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                FloorFree dialog = new FloorFree(new javax.swing.JFrame(), true,chua);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btnchoseu;
    private javax.swing.JButton btnexit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbdulieu;
    private javax.swing.JButton btnInsert;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    // End of variables declaration
    
    private void btnchoseuActionPerformed(java.awt.event.ActionEvent evt) {
    	for (int j = 0 ; j < tbdulieu.getRowCount();j++)
		{		
			if(tbdulieu.getValueAt(j, 0).toString() == "true")
			{							
				UnitFree unif = new UnitFree(null,true,tbdulieu.getValueAt(j, 3).toString());
				unif.setFloorId(a3);
				unif.setCheckviable("open");
				unif.setVisible(true);
				while (unif.isVisible() != true) {
		                    if (unif.getCheckviable().equals("close")) {
		                        if(unif.getCountvalueunit() == 0)
		                        {
		                            try {                                     
	                                        Registry registry = LocateRegistry.getRegistry(connectRMI.host,connectRMI.port);
	                                        EtowInterface obj=(EtowInterface)registry.lookup(connectRMI.regis);
	                                        String floorName = tbdulieu.getValueAt(j,1).toString();
	                                        String status = "1";
	                                        int id = Integer.parseInt(tbdulieu.getValueAt(j,3).toString());
	                                        obj.EditFloor(floorName,status,id );
	                                        
        	                                }catch(Exception ex){
        	                                        
        	                                }
        	                                reloadtable();
		                        }
		                        else
		                        {
		                            reloadtable();
		                        }
		                        break;
		                    }
		                }
			}																    
		}
    }

    private void reloadtable()
    {
        while (tbdulieu.getRowCount() != 0) {
            dtm.removeRow(0);
            }

        try {                            
                 Registry registry = LocateRegistry.getRegistry(connectRMI.host,connectRMI.port);
                 EtowInterface obj=(EtowInterface)registry.lookup(connectRMI.regis);
                
                List<GroupClass.FloorClass> x =obj.showfloorfreeoftown(getTownId());
                        
                for(GroupClass.FloorClass d:x) {
                        floorId = d.getIdfloor();
                floorName = d.getNamefloor();
                statusFloor = d.getStatusfloor();               
                dtm.addRow(new Object[]{new Boolean(false),floorName,statusFloor,floorId});
                }
                        
            }catch (Exception ex) {
                        ex.printStackTrace();
            }

    }

    private void btnexitActionPerformed(java.awt.event.ActionEvent evt) {
    	setVisible(false);
    	setCheckVisable("close");
    	setCountFloor(tbdulieu.getRowCount());
    }
    
    
    class MyItemListener implements ItemListener  
    {  
     public void itemStateChanged(ItemEvent e) {  
        Object source = e.getSource();  
        if (source instanceof AbstractButton == false) return;  
        boolean checked = e.getStateChange() == ItemEvent.SELECTED;  
        for(int x = 0, y = tbdulieu.getRowCount(); x < y; x++)  
        {  
        	tbdulieu.setValueAt(new Boolean(checked),x,0);  
        }  
      }  
    }
    
    public static String getA1() {
		return a1;
	}

	public static String getA2() {
		return a2;
	}

	public static String getA3() {
		return a3;
	}
}
